package com.example.sharedpreferencesdemo;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;

import javax.security.auth.login.LoginException;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private EditText data;
    private Button save;
    private TextView showData;
    private Button getData;
    private CheckBox cb;
    private  SharedPreferences.Editor editor;
    private SharedPreferences sp;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        editor = getSharedPreferences("data",MODE_PRIVATE).edit();
        sp = getSharedPreferences("data",MODE_PRIVATE);
        initView();

        if(sp.getBoolean("cb",false)){
            showData.setText(sp.getString("ip","192.168.1.1"));
        }
    }

    private void initView() {
        data = (EditText) findViewById(R.id.data);
        save = (Button) findViewById(R.id.save);
        showData = (TextView) findViewById(R.id.showData);
        getData = (Button) findViewById(R.id.getData);
        cb = findViewById(R.id.cb);
        save.setOnClickListener(this);
        getData.setOnClickListener(this);
        cb.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.save:
                editor.putString("ip",data.getText().toString());
                editor.apply();
                break;
            case R.id.getData:
                showData.setText(sp.getString("ip","192.168.1.1"));
                break;
            case R.id.cb:
                editor.putBoolean("cb",cb.isChecked());
                editor.apply();
                Log.e("isCheck",String.valueOf(sp.getBoolean("cb",false)));
                break;
        }
    }


}
